package com.gree.scmservice.controller;

import com.gree.common.annotation.Log;
import com.gree.common.entity.ReturnVo;
import com.gree.common.enums.BusinessType;
import com.gree.common.service.ISysOperLogService;
import com.gree.common.utils.StringUtils;
import com.gree.framework.entity.CusUserDetails;
import com.gree.framework.manager.AsyncManager;
import com.gree.framework.manager.factory.AsyncFactory;
import com.gree.framework.utils.SecurityUtils;
import com.gree.scmservice.dao.MenuDao;
import com.gree.scmservice.entity.smbse.SysMenuMo;
import com.gree.scmservice.service.GscmMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.cxf.security.claims.authorization.Claims;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by 180686 on 2021/3/16 20:22
 */


@RestController
@RequestMapping("/menu")
@Api(tags = "系统信息:菜单接口")
public class MenuController {

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private GscmMenuService gscmMenuService;

    @Autowired
    private ISysOperLogService iSysOperLogService;

    /**
     * Jwt模式获取菜单
     * @param styp
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/getMenuJsonJwt")
    public List<Map<String, Object>> getMenuJsonJwt(@RequestParam(value = "styp", required = false, defaultValue = "0") int styp, HttpServletRequest request) throws UnsupportedEncodingException {
        /*Jwt 模式 */
        List<Map<String, Object>> dicList = new ArrayList<Map<String, Object>>();
        /*String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header, "Bearer ");
        Claims claims = Jwts.parser()
                .setSigningKey("internet_plus".getBytes("utf-8"))
                .parseClaimsJws(token).getBody();
        String comp = String.valueOf(claims.get("comp"));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String temp = "";
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            temp = (new StringBuilder(String.valueOf(temp))).append("'")
                    .append(authority.getAuthority()).append("',").toString();
        }
        //当前节点信息
        dicList = menuDao.findTenorByRoleAndFono(comp,temp,0);
        //调用递归子集节点信息
        menuDao.findMenuTreeByRole(comp,temp,0,styp,dicList);*/
        return dicList;
    }

    /**
     * 目前获取菜单接口
     * @param styp
     * @return
     */
    @GetMapping("/getMenuJson")
    @ApiOperation(value = "目前获取菜单接口")
    @ApiImplicitParam(name = "styp", value = "系统订单信息", dataType = "int")
    public List<Map<String, Object>> getMenuJson(@RequestParam(value = "styp", required = false, defaultValue = "0") int styp) {
        CusUserDetails cusUserDetails = SecurityUtils.getUser();
        String comp = cusUserDetails.getComp();
        String temp = "";
        Collection<? extends GrantedAuthority> authorities = SecurityUtils.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            temp = (new StringBuilder(String.valueOf(temp))).append("'")
                    .append(authority.getAuthority()).append("',").toString();
        }
        List<Map<String, Object>> dicList = new ArrayList<Map<String, Object>>();
        //当前节点信息
        /*dicList = menuDao.findTenorByRoleAndFono(comp,temp,0);*/
        //调用递归子集节点信息
        if (styp == 0) {
            return dicList;
        }

        dicList = menuDao.selectMenuTreeByUserId(comp,temp,0,styp);

        return dicList;
    }

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo list(SysMenuMo sysMenuMo)
    {
        List<SysMenuMo> list = gscmMenuService.selectMenuList(sysMenuMo);
        return new ReturnVo("200","success",list);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    @ApiOperation(value = "根据菜单编号获取详细信息")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo getInfo(@PathVariable String menuId)
    {
        return new ReturnVo("200","success",gscmMenuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo treeselect(SysMenuMo sysMenuMo2)
    {
        SysMenuMo sysMenuMo = new SysMenuMo();
        sysMenuMo.setStyp(0);
        sysMenuMo.setParentId(0L);
        ArrayList result = new ArrayList();

        List<SysMenuMo> list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(1);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(2);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(3);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(4);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        NutMap nutMap = NutMap.NEW().addv("menus", result);
        return new ReturnVo("200","success",nutMap);
    }


    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleKey}")
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo roleMenuTreeselect(@PathVariable("roleKey") String roleKey)
    {
        SysMenuMo sysMenuMo = new SysMenuMo();
        sysMenuMo.setStyp(0);
        sysMenuMo.setParentId(0L);
        ArrayList result = new ArrayList();

        List<SysMenuMo> list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(1);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(2);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(3);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        sysMenuMo.setStyp(4);
        list = gscmMenuService.selectMenuList(sysMenuMo);
        result.add(gscmMenuService.buildMenuTreeSelect(list));

        NutMap nutMap = NutMap.NEW().addv("checkedKeys", gscmMenuService.selectMenuListByRoleKey(roleKey)).addv("menus", result);
        return new ReturnVo("200","success",nutMap);
    }

    /**
     * 新增菜单
     */

    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo add(@Validated @RequestBody SysMenuMo sysMenuMo)
    {
        if(gscmMenuService.checkMenuIDUnique(sysMenuMo)){
            return new ReturnVo("500","新增菜单'" + sysMenuMo.getMenuId() + "'失败，菜单ID已存在");
        }
        else if (sysMenuMo.getMenuId().equals(sysMenuMo.getParentId()))
        {
            return new ReturnVo("500","修改菜单'" + sysMenuMo.getMenuId() + "'失败，上级菜单不能选择自己");
        }
        int resultNum = gscmMenuService.insertMenu(sysMenuMo);
        if(resultNum > 0){
            return new ReturnVo("200","success");
        }else{
            return new ReturnVo("500","fail");
        }
    }
    /**
     * 修改菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo edit(@Validated @RequestBody SysMenuMo sysMenuMo)
    {
        if (sysMenuMo.getMenuId().equals(sysMenuMo.getParentId()))
        {
            return new ReturnVo("500","修改菜单'" + sysMenuMo.getMenuId() + "'失败，上级菜单不能选择自己");
        }
        int result = gscmMenuService.updateMenu(sysMenuMo);
        return new ReturnVo("200","success");
    }

    /**
     * 删除菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public ReturnVo remove(@PathVariable("menuId") String menuId)
    {
        if (gscmMenuService.hasChildByMenuId(menuId))
        {
            return new ReturnVo("500","存在子菜单,不允许删除");
        }
        if (gscmMenuService.checkMenuExistRole(menuId))
        {
            return new ReturnVo("500","菜单已分配,不允许删除");
        }
        int result = gscmMenuService.deleteMenuById(menuId);
        return new ReturnVo("200","success");
    }

    @GetMapping(value = "/recordmenu/{teno}")
    @ApiOperation(value = "获取菜单列表")
    @ApiImplicitParam(name = "sysMenuMo", value = "获取菜单列表", dataType = "SysMenuMo")
    public void recordMenu(@PathVariable("teno") String teno){
        String usid = SecurityUtils.getUser().getUsername();
        String comp = SecurityUtils.getUser().getComp();
        AsyncManager.me().execute(AsyncFactory.recordMenu(usid,comp,teno));
    }
}